package com.xiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiao.mapper.BlogSysUserMapper;
import com.xiao.domain.pojo.BlogSysUser;
import com.xiao.domain.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service // 用我们这个代替系统的bean
public class UserDetailsServiceImpl implements UserDetailsService {
// UserDetailsService 是系统的 接口
    @Autowired
    BlogSysUserMapper blogSysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 编写 查询条件
        LambdaQueryWrapper<BlogSysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlogSysUser::getUserName,username);

        // 2. 查询用户
        BlogSysUser blogSysUser = blogSysUserMapper.selectOne(wrapper);

        // 3.判断是否查询到数据，否则抛出异常
        if (Objects.isNull(blogSysUser)){
            throw new RuntimeException("用户不存在");
        }
        // 4. 返回用户信息，使用 LoginUser 进行封装 让他和 UserDetails 交互。 因为 他实现了 UserDetails
        LoginUser loginUser = new LoginUser(blogSysUser);
        return loginUser;
    }
}
